﻿// 公共事件参数类和闹钟类库
using System.Reflection.Emit;

public class TickEventArgs : EventArgs
{
    public DateTime CurrentTime { get; set; }
}

public class AlarmEventArgs : EventArgs
{
    public DateTime AlarmTime { get; set; }
}

public class AlarmClock
{
    private readonly System.Timers.Timer _timer;
    private DateTime? _alarmTime;

    public event EventHandler<TickEventArgs> Tick;
    public event EventHandler<AlarmEventArgs> Alarm;

    public AlarmClock()
    {
        _timer = new System.Timers.Timer(1000); // 1秒间隔
        _timer.Elapsed += TimerElapsed;
    }

    public DateTime? AlarmTime
    {
        get => _alarmTime;
        set => _alarmTime = value?.AddMilliseconds(-value.Value.Millisecond); // 去除毫秒
    }

    public void Start() => _timer.Start();
    public void Stop() => _timer.Stop();

    private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        var now = DateTime.Now;
        var current = now.AddMilliseconds(-now.Millisecond); // 精确到秒

        Tick?.Invoke(this, new TickEventArgs { CurrentTime = current });

        if (_alarmTime.HasValue && current >= _alarmTime.Value)
        {
            Alarm?.Invoke(this, new AlarmEventArgs { AlarmTime = _alarmTime.Value });
            _alarmTime = null; // 单次触发后重置
        }
    }
}

class Program
{
    static void Main()
    {
        int t = 5; // 闹钟时间，单位为秒
        var alarmClock = new AlarmClock();
        alarmClock.AlarmTime = DateTime.Now.AddSeconds(t);

        alarmClock.Tick += (s, e) =>
            Console.WriteLine($"滴答... 当前时间: {e.CurrentTime:HH:mm:ss}");

        alarmClock.Alarm += (s, e) =>
            Console.WriteLine($"闹铃响了！设定时间: {e.AlarmTime:HH:mm:ss}");

        alarmClock.Start();
        Console.WriteLine("闹钟已启动，{0}秒后响铃...",t);
        Console.ReadLine();
    }
}
